package com.py.credit.controller;

import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.constant.LhjcTableNameConstant;
import com.py.credit.entity.GzObj;
import com.py.credit.entity.Removal;
import com.py.credit.entity.SysUser;
import com.py.credit.service.GzService;
import com.py.credit.service.LhjcAjbhService;
import com.py.credit.service.LhjcRemoteBaseService;
import com.py.credit.service.RemovalService;
import com.py.credit.utils.IdcardValidator;
import com.py.framework.core.helper.HttpServletHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;

/**
 * 联合奖惩事件发起controller
 */
@RestController
@RequestMapping(value = "/ajfq")
public class LhjcAjbhController {

    @Autowired
    private LhjcRemoteBaseService remoteBaseService;

    @Autowired
    private LhjcAjbhService lhjcAjbhService;

    @Autowired
    private GzService gzService;

    @Autowired
    private RemovalService removalService;

    /**
     * 判断红黑名单是否在其他事件库
     *
     * @param jclb
     * @param type
     * @param ztmc
     * @param bm
     * @param request
     * @return
     */
    @RequestMapping(value = "/detailIsExistOtherStorage.do", method = RequestMethod.POST)
    public RestServiceResult<Boolean> detailIsExistOtherStorage(@RequestParam(defaultValue = "", required = true, value = "recordId") String recordId,
                                                                @RequestParam(defaultValue = "", required = true, value = "jclb") String jclb,
                                                                @RequestParam(defaultValue = "", required = true, value = "type") String type,
                                                                @RequestParam(defaultValue = "", required = true, value = "ztmc") String ztmc,
                                                                @RequestParam(defaultValue = "", required = true, value = "bm") String bm,
                                                                @RequestParam(defaultValue = "", required = true, value = "isCheck") String isCheck,
                                                                HttpServletRequest request) {
        Boolean result = true;

        if (isCheck.equals("N")) {
            String jdToken = HttpServletHelper.getUserToken(request);
            if (StringUtils.isNotBlank(jdToken)) {
                try {
                    result = lhjcAjbhService.detailIsExistOtherStorage(jclb, type, ztmc, bm);
                } catch (Exception e) {
                    ExceptionLogger.error(e);
                }
            }
        } else {
            try {
                result = lhjcAjbhService.detailIsExistOtherStorage(jclb, type, ztmc, bm);
            } catch (Exception e) {
                ExceptionLogger.error(e);
            }
        }

        if (result) {
            lhjcAjbhService.addAjfqErrLog(recordId, LhjcTableNameConstant.getTableName(jclb, type), "该信用主体已在其他库中存在");
        }

        return new RestServiceResult(result);
    }

    /**
     * 添加法人联合奖惩事件
     *
     * @param jclb
     * @param tybm
     * @param qymc
     * @param tyshxydm
     * @param zzjgdm
     * @param gsdjm
     * @param gzName
     * @param ysajh
     * @param cfqx
     * @param request
     * @return
     */
    @RequestMapping(value = "/addFrLhjcAjbh.do", method = RequestMethod.POST)
    public RestServiceResult<Boolean> addFrLhjcAjbh(@RequestParam(defaultValue = "", required = true, value = "recordId") String recordId,
                                                    @RequestParam(defaultValue = "", required = true, value = "jclb") String jclb,
                                                    @RequestParam(value = "tybm", defaultValue = "", required = true) String tybm,
                                                    @RequestParam(value = "qymc", defaultValue = "", required = true) String qymc,
                                                    @RequestParam(value = "tyshxydm", defaultValue = "", required = true) String tyshxydm,
                                                    @RequestParam(value = "zzjgdm", defaultValue = "", required = true) String zzjgdm,
                                                    @RequestParam(value = "gsdjm", defaultValue = "", required = true) String gsdjm,
                                                    @RequestParam(value = "gzName", defaultValue = "", required = true) String gzName,
                                                    @RequestParam(value = "ysajh", defaultValue = "", required = true) String ysajh,
                                                    @RequestParam(value = "cfqx", defaultValue = "", required = true) String cfqx,
                                                    @RequestParam(value = "isCheck", defaultValue = "", required = true) String isCheck,
                                                    @RequestParam(value = "username", defaultValue = "", required = true) String username,
                                                    HttpServletRequest request) {
        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;

        String tableName = LhjcTableNameConstant.getTableName(jclb, "C");

        if (isCheck.equals("N") || isCheck.equals("C")) {
            if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
                userInfo = user.getData();
                if (null != userInfo) {

                } else {
                    lhjcAjbhService.addAjfqErrLog(recordId, tableName, "未获取到当前用户信息");
                    ExceptionLogger.error("LhjcAjbhController#addFrLhjcAjbh", "未获取到当前用户信息！");
                    return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
                }
            } else {
                lhjcAjbhService.addAjfqErrLog(recordId, tableName, "未获取到当前用户信息");
                ExceptionLogger.error("LhjcAjbhController#addFrLhjcAjbh", "未获取到当前用户信息！");
                return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
            }
        } else if (isCheck.equals("Y")) {
            userInfo = remoteBaseService.getByUsername(username);
        }

        //统一编码不能为空
        if (tybm == null || tybm.trim().equals("")) {
            lhjcAjbhService.addAjfqErrLog(recordId, tableName, "统一编码不能为空");
            return new RestServiceResult(false);
        }

        //惩戒原始案件号不能为空
        if (jclb.equals("C")) {
            if (ysajh == null || ysajh.trim().equals("")) {
                lhjcAjbhService.addAjfqErrLog(recordId, tableName, "惩戒原始案件号不能为空");
                return new RestServiceResult(false);
            }
        }

        Date now = new Date();

        //判断截止日期是否符合格式
        String reg = "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))$";

        if (!cfqx.matches(reg)) {
            //截止日期格式错误
            lhjcAjbhService.addAjfqErrLog(recordId, tableName, "截止日期格式错误");
            return new RestServiceResult(false);
        }

        //判断日期是否比生效日期大
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if (sdf.parse(cfqx).getTime() < now.getTime()) {
                //截止日期不能小于当前日期
                lhjcAjbhService.addAjfqErrLog(recordId, tableName, "截止日期不能小于当前日期");
                return new RestServiceResult(false);
            }
        } catch (ParseException e) {
            //截止日期格式错误
            lhjcAjbhService.addAjfqErrLog(recordId, tableName, "截止日期格式错误");
            return new RestServiceResult(false);
        }

        GzObj gzObj = gzService.selectByGzName(gzName);
        if (gzObj == null) {
            //联合奖惩规则数据库中不存在
            lhjcAjbhService.addAjfqErrLog(recordId, tableName, "联合奖惩规则数据库中不存在");
            return new RestServiceResult(false);
        }

        if (!gzObj.getJclb().equals(jclb)) {
            //联合奖惩规则类型错误
            lhjcAjbhService.addAjfqErrLog(recordId, tableName, "联合奖惩规则类型错误");
            return new RestServiceResult(false);
        }

        if (gzService.selectCsIsExistByGzId(gzObj.getId(), jclb, "C") < 1) {
            //联合奖惩规则无对应的措施
            lhjcAjbhService.addAjfqErrLog(recordId, tableName, "联合奖惩规则无对应的措施");
            return new RestServiceResult(false);
        }

        //判断机构信息是否还在处罚中
        Date jzrqDate = lhjcAjbhService.selectJzrqDate(jclb, qymc, null, gzObj.getBm(), ysajh);

        try {
            //机构还在处罚中
            if (null != jzrqDate) {
                if (now.getTime() <= jzrqDate.getTime() || sdf.format(now).equals(sdf.format(jzrqDate)) || sdf.parse(cfqx).getTime() <= jzrqDate.getTime()) {
                    lhjcAjbhService.addAjfqErrLog(recordId, tableName, "截止日期内还有该信用主体的奖惩信息");
                    return new RestServiceResult(false);
                }
            }
        } catch (ParseException e) {
            lhjcAjbhService.addAjfqErrLog(recordId, tableName, "截止日期格式错误");
            return new RestServiceResult(false);
        }

        if (!isCheck.equals("C")) {
            lhjcAjbhService.addFr(gzObj, jclb, tybm, qymc, tyshxydm, zzjgdm, gsdjm, cfqx, now, userInfo.getId(), userInfo.getOfficeId(), ysajh, HttpServletHelper.getUserToken(request), userInfo);
        }

        return new RestServiceResult(true);
    }

    /**
     * 添加自然人联合奖惩事件
     *
     * @param jclb
     * @param tybm
     * @param xm
     * @param bm
     * @param gzName
     * @param ysajh
     * @param cfqx
     * @param request
     * @return
     */
    @RequestMapping(value = "/addZrrLhjcAjbh.do", method = RequestMethod.POST)
    public RestServiceResult<Boolean> addZrrLhjcAjbh(@RequestParam(defaultValue = "", required = true, value = "recordId") String recordId,
                                                     @RequestParam(defaultValue = "", required = true, value = "jclb") String jclb,
                                                     @RequestParam(value = "tybm", defaultValue = "", required = true) String tybm,
                                                     @RequestParam(value = "xm", defaultValue = "", required = true) String xm,
                                                     @RequestParam(value = "bm", defaultValue = "", required = true) String bm,
                                                     @RequestParam(value = "gzName", defaultValue = "", required = true) String gzName,
                                                     @RequestParam(value = "ysajh", defaultValue = "", required = true) String ysajh,
                                                     @RequestParam(value = "cfqx", defaultValue = "", required = true) String cfqx,
                                                     @RequestParam(value = "isCheck", defaultValue = "", required = true) String isCheck,
                                                     @RequestParam(value = "username", defaultValue = "", required = true) String username,
                                                     HttpServletRequest request) {
        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;

        String tableName = LhjcTableNameConstant.getTableName(jclb, "P");

        if (isCheck.equals("N") || isCheck.equals("C")) {
            if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
                userInfo = user.getData();
                if (null != userInfo) {

                } else {
                    lhjcAjbhService.addAjfqErrLog(recordId, tableName, "未获取到当前用户信息");
                    ExceptionLogger.error("LhjcAjbhController#addZrrLhjcAjbh", "未获取到当前用户信息！");
                    return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
                }
            } else {
                lhjcAjbhService.addAjfqErrLog(recordId, tableName, "未获取到当前用户信息");
                ExceptionLogger.error("LhjcAjbhController#addZrrLhjcAjbh", "未获取到当前用户信息！");
                return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
            }
        } else if (isCheck.equals("Y")) {
            userInfo = remoteBaseService.getByUsername(username);
        }

        //统一编码不能为空
        if (tybm == null || tybm.trim().equals("")) {
            lhjcAjbhService.addAjfqErrLog(recordId, tableName, "统一编码不能为空");
            return new RestServiceResult(false);
        }

        //惩戒原始案件号不能为空
        if (jclb.equals("C")) {
            if (ysajh == null || ysajh.trim().equals("")) {
                lhjcAjbhService.addAjfqErrLog(recordId, tableName, "惩戒原始案件号不能为空");
                return new RestServiceResult(false);
            }
        }

        //身份证号码校验
        IdcardValidator check = new IdcardValidator();

        if (!check.run(bm, "")) {
            //身份证号码格式错误
            lhjcAjbhService.addAjfqErrLog(recordId, tableName, "身份证号码格式错误");
            return new RestServiceResult(false);
        }

        Date now = new Date();

        //判断截止日期是否符合格式
        String reg = "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))$";

        if (!cfqx.matches(reg)) {
            //截止日期格式错误
            lhjcAjbhService.addAjfqErrLog(recordId, tableName, "截止日期格式错误");
            return new RestServiceResult(false);
        }

        //判断日期是否比生效日期大
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if (sdf.parse(cfqx).getTime() < now.getTime()) {
                //截止日期不能小于当前日期
                lhjcAjbhService.addAjfqErrLog(recordId, tableName, "截止日期不能小于当前日期");
                return new RestServiceResult(false);
            }
        } catch (ParseException e) {
            //截止日期格式错误
            lhjcAjbhService.addAjfqErrLog(recordId, tableName, "截止日期格式错误");
            return new RestServiceResult(false);
        }

        GzObj gzObj = gzService.selectByGzName(gzName);
        if (gzObj == null) {
            //联合奖惩规则数据库中不存在
            lhjcAjbhService.addAjfqErrLog(recordId, tableName, "联合奖惩规则数据库中不存在");
            return new RestServiceResult(false);
        }

        if (!gzObj.getJclb().equals(jclb)) {
            //联合奖惩规则类型错误
            lhjcAjbhService.addAjfqErrLog(recordId, tableName, "联合奖惩规则类型错误");
            return new RestServiceResult(false);
        }

        if (gzService.selectCsIsExistByGzId(gzObj.getId(), jclb, "P") < 1) {
            //联合奖惩规则无对应的措施
            lhjcAjbhService.addAjfqErrLog(recordId, tableName, "联合奖惩规则无对应的措施");
            return new RestServiceResult(false);
        }

        //判断机构信息是否还在处罚中
        Date jzrqDate = lhjcAjbhService.selectJzrqDate(jclb, null, bm, gzObj.getBm(), ysajh);

        try {
            //机构还在处罚中
            if (null != jzrqDate) {
                if (now.getTime() <= jzrqDate.getTime() || sdf.format(now).equals(sdf.format(jzrqDate)) || sdf.parse(cfqx).getTime() <= jzrqDate.getTime()) {
                    lhjcAjbhService.addAjfqErrLog(recordId, tableName, "截止日期内还有该信用主体的奖惩信息");
                    return new RestServiceResult(false);
                }
            }
        } catch (ParseException e) {
            lhjcAjbhService.addAjfqErrLog(recordId, tableName, "截止日期格式错误");
            return new RestServiceResult(false);
        }

        if (!isCheck.equals("C")) {
            lhjcAjbhService.addZrr(gzObj, jclb, tybm, xm, bm, cfqx, now, userInfo.getId(), userInfo.getOfficeId(), ysajh, HttpServletHelper.getUserToken(request), userInfo);
        }

        return new RestServiceResult(true);
    }

    @RequestMapping(value = "/addZrrLhcjGlcf.do", method = RequestMethod.POST)
    public RestServiceResult<LinkedHashMap> addZrrLhcjGlcf(@RequestParam(value = "tybm", defaultValue = "", required = true) String tybm,
                                                     @RequestParam(value = "xm", defaultValue = "", required = true) String xm,
                                                     @RequestParam(value = "zjtype", defaultValue = "", required = true) String zjtype,
                                                     @RequestParam(value = "idcard", defaultValue = "", required = true) String idcard,
                                                     @RequestParam(value = "position", defaultValue = "", required = true) String position,
                                                     @RequestParam(value = "frajbh", defaultValue = "", required = true) String frajbh,
                                                     @RequestParam(value = "ysajh", defaultValue = "", required = true) String ysajh,
                                                     @RequestParam(value = "cfqx", defaultValue = "", required = true) String cfqx,
                                                     HttpServletRequest request) {
        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;

        LinkedHashMap linkedHashMap=new LinkedHashMap();

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null != userInfo) {

            } else {
                ExceptionLogger.error("LhjcAjbhController#addZrrLhcjGlcf", "未获取到当前用户信息！");
                return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("LhjcAjbhController#addZrrLhcjGlcf", "未获取到当前用户信息！");
            return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
        }

        Date now = new Date();

        //判断截止日期是否符合格式
        String reg = "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))$";

        if (!cfqx.matches(reg)) {
            //截止日期格式错误
            linkedHashMap.put("flag","false");
            linkedHashMap.put("errLog","截止日期格式错误");
            return new RestServiceResult(linkedHashMap);
        }

        //判断日期是否比生效日期大
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if (sdf.parse(cfqx).getTime() < now.getTime()) {
                //截止日期不能小于当前日期
                linkedHashMap.put("flag","false");
                linkedHashMap.put("errLog","截止日期不能小于当前日期");
                return new RestServiceResult(linkedHashMap);
            }
        } catch (ParseException e) {
            //截止日期格式错误
            linkedHashMap.put("flag","false");
            linkedHashMap.put("errLog","截止日期格式错误");
            return new RestServiceResult(linkedHashMap);
        }

        Removal removal = removalService.selectInfo(frajbh);
        if (removal == null) {
            //法人事件不存在
            linkedHashMap.put("flag","false");
            linkedHashMap.put("errLog","法人事件不存在");
            return new RestServiceResult(linkedHashMap);
        }

        if (!removal.getStatus().equals("J")) {
            //法人事件已移出
            linkedHashMap.put("flag","false");
            linkedHashMap.put("errLog","法人事件已移出");
            return new RestServiceResult(linkedHashMap);
        }

        if (!removal.getJclb().equals("C")) {
            //联合奖惩规则类型错误
            linkedHashMap.put("flag","false");
            linkedHashMap.put("errLog","联合奖惩规则类型错误");
            return new RestServiceResult(linkedHashMap);
        }

        if (gzService.selectCsIsExistByGzId(removal.getGzId(), "C", "P") < 1) {
            //联合奖惩规则无对应的措施
            linkedHashMap.put("flag","false");
            linkedHashMap.put("errLog","联合奖惩规则无对应的措施");
            return new RestServiceResult(linkedHashMap);
        }

        //判断机构信息是否还在处罚中
        Date jzrqDate = lhjcAjbhService.selectJzrqDate("C", null, idcard, removal.getGzbm(), ysajh);

        try {
            //机构还在处罚中
            if (null != jzrqDate) {
                if (now.getTime() <= jzrqDate.getTime() || sdf.format(now).equals(sdf.format(jzrqDate)) || sdf.parse(cfqx).getTime() <= jzrqDate.getTime()) {
                    linkedHashMap.put("flag","false");
                    linkedHashMap.put("errLog","机构还在处罚中");
                    return new RestServiceResult(linkedHashMap);
                }
            }
        } catch (ParseException e) {
            linkedHashMap.put("flag","false");
            linkedHashMap.put("errLog","机构还在处罚中");
            return new RestServiceResult(linkedHashMap);
        }

        return new RestServiceResult(lhjcAjbhService.addZrrGlcf(removal, xm, zjtype, idcard, position, cfqx, frajbh, now, userInfo.getId(), userInfo.getOfficeId(), ysajh, HttpServletHelper.getUserToken(request), userInfo, gzService.selectById(removal.getGzId() + "")));
    }

    /**
     * 查询错误日志
     *
     * @param recordId 记录id
     * @param jclb     奖惩类别：C:惩戒 J:激励
     * @param type     主体类型：C:法人 P:自然人
     * @return
     */
    @RequestMapping(value = "/selectErrInfo.do", method = RequestMethod.POST)
    public RestServiceResult<LinkedHashMap> selectErrInfo(@RequestParam(value = "recordId", defaultValue = "", required = true) String recordId,
                                                          @RequestParam(value = "jclb", defaultValue = "", required = true) String jclb,
                                                          @RequestParam(value = "type", defaultValue = "", required = true) String type) {
        String tableName = LhjcTableNameConstant.getTableName(jclb, type);
        return new RestServiceResult(lhjcAjbhService.selectAjfqErrInfo(recordId, tableName));
    }
}
